package cn.ruihusoft.ql.core;

import cn.hutool.core.util.StrUtil;
import cn.ruihusoft.ql.pojo.Response;
import cn.ruihusoft.ql.pojo.user.UserTokenResponse;
import cn.ruihusoft.ql.service.UserService;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthInterceptor implements Interceptor<Response> {

    private static final Object LOCK = new Object();

    private UserTokenResponse token;

    @Autowired
    private UserService userService;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        // 获取Token
        refreshToken();

        // 将token设置在header上
        request.addHeader("Authorization", StrUtil.format("{} {}", token.getTokenType(), token.getToken()));

        return true;
    }

    private void refreshToken() {
        if (!needRefresh())
            return;

        synchronized (LOCK) {
            if (!needRefresh())
                return;

            token = userService.token(QlSdkInit.getClientId(), QlSdkInit.getClientSecret());
        }
    }

    private boolean needRefresh() {
        if (token == null)
            return true;

        return token.getExpiration() < System.currentTimeMillis() / 1000L;
    }
}
